/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ToggleButton;

/**Activity that shows a list of all Rules*/
public class RuleList extends ProfileList {
    private static final int MENU_EXIT = Menu.FIRST;
    private static final int MEN_DELETE_ID = Menu.FIRST+1;
    private Long MenOpenFor = -1L;
    private Long EditRuleNo = -1L;
    private static Activity act;
    

    @SuppressWarnings("static-access")
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		final long id = Long.parseLong((String)v.getTag());
		if(id==-1)
		{
			return;
		}
		Cursor notesCursor = super.mDbHelper.fetchRule(id);
		if(notesCursor!=null)
		{
			menu.setHeaderTitle(notesCursor.getString(notesCursor.getColumnIndex(Database.R_KEY_NAME)));
			notesCursor.close();
		}
		MenOpenFor = id;
		menu.clear();
        menu.add(0, MEN_DELETE_ID, 0, R.string.menu_delete).setOnMenuItemClickListener(Contextmen);;
        
	}
	private MenuItem.OnMenuItemClickListener Contextmen = new
	MenuItem.OnMenuItemClickListener(){

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			onContextItemSelected(item);
			return false;
		}
		
		
	};
    @Override
	public boolean onContextItemSelected(MenuItem item) {


		if(MenOpenFor==-1L)
    	{
    		return true;
    	}
		switch(item.getItemId()) {
    	case MEN_DELETE_ID:
    		mDbHelper.deleteRule(MenOpenFor);
    		setupTableView(this);
	        return true;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		
		menu.clear();

		//Help
		final Intent helpIntent = new Intent(this, OnlineHelp.class);//("com.twofortyfouram.locale.intent.action.HELP");
		helpIntent.putExtra(OnlineHelp.HELP_URL, OnlineHelp.HELP_URL_PRE+"rules");
		helpIntent.putExtra(TimedProfiles.INTENT_TITLE, getTitle().toString());

		menu.add(0, MENU_EXIT, 0, R.string.men_exit)
		 .setIcon(android.R.drawable.ic_lock_power_off).getItemId();

		menu.add(R.string.onlinehelp)
			.setIcon(android.R.drawable.ic_menu_help).setIntent(helpIntent);

		//New
		MenuItem i = menu.add(R.string.rule_add).setIcon(android.R.drawable.ic_menu_add);
		if(TimedProfiles.car_mode)
		{
			i.setEnabled(false);
		}else{
			Intent NewRule = new Intent(this, RuleEditor.class); 
			NewRule.putExtra(RuleEditor.OpenParam_RuleID, "-1");
			i.setIntent(NewRule);
		}

		return true;
	}
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item)
	{
		switch (item.getItemId())
		{
			case MENU_EXIT:
			{
				finish();
				return true;
			}
		}

		return super.onOptionsItemSelected(item);
	}
    
    @Override
    protected void onResume() {
    	mDbHelper.open();
    	if(EditRuleNo!=-1L)
    	{
    		//rule was on before editing -> switch on again
    		mDbHelper.updateRule(EditRuleNo, null, 1, -1, 0, -1);
    		EditRuleNo=-1L;
    		TimedProfiles.aktTimer(this);
    	}
        super.onResume();
    }
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        act = this;
        
        super.ShowRules = true;
    }

    public void onClick(View v) {
        // Perform action on click
    	
    	if(v.getId()==R.id.ToggleButton01)
    	{
    		mDbHelper.updateRule(Long.parseLong((String) ((View) v.getParent()).getTag()), null, ((ToggleButton)v).isChecked()?1:0, -1, -1, -1);
        	//start or stop the periodic rule check if nesecary
			int[] r = mDbHelper.fetchReadyRules();
			if(r[0]>0)
			{
		        long d = mDbHelper.getNextDeadLine();
		        if(d!=0)
		        {
		        	TimedProfiles.aktTimerOnce(act, d);
		        }
			}
			if(r[1]>0)
			{
    			TimedProfiles.aktTimer(act);
    		}else{
    			TimedProfiles.deaktTimer(act);
			}
    	}else{
        	if(TimedProfiles.car_mode)
        	{
        		//dont edit, toggle!
        		((ViewGroup) v).getChildAt(((ViewGroup) v).getChildCount()-1).performClick();
        	}else{
	    		Intent Opener = new Intent(act, RuleEditor.class); 
	    		Opener.putExtra(RuleEditor.OpenParam_RuleID, (CharSequence)v.getTag());
	    		//startActivityForResult(Opener, 0);
	    		
	    		if(((ToggleButton)v.findViewById(R.id.ToggleButton01)).isChecked())
	    		{
		    		//switch rule off while editing
		    		EditRuleNo = Long.parseLong((String)v.getTag());
		    		mDbHelper.updateRule(EditRuleNo, null, 0, -1, -1, -1);
	    		}
	    		
	    		act.startActivityForResult(Opener,0);
        	}
    	}
    }
}
